<template>
    <div>
        <div class="edu-opertion-bar">
            <div class="float-left"/>
            <div class="float-left">
                <span
                    v-for="(item, value) in topNavItems"
                    :class="{active: item.active}"
                    :key="value"
                    class="border-right"
                    @click="clickItem(item)"
                >{{ item.label }} |</span>
            </div>
            <div class="float-right">
                <el-button
                    type="primary"
                    @click="addDirection"
                    v-if="!isRead"
                >{{$t('culture.profession.addDirection')}}</el-button>
            </div>
        </div>
        <div v-if="next" class="tip-message">{{ tip }}</div>
        <el-table :data="processedData" :span-method="arraySpanMethod" border>
            <el-table-column prop="name" :label="$t('culture.course.category')" align="center"/>
            <el-table-column :label="$t('culture.courseCategory.subName')">
                <template slot-scope="props">
                    <span
                        v-bind:class="{'new-record': inChange&&props.row.changeStatus == 1,'edit-record': inChange&&props.row.changeStatus == 2,'remove-record': inChange&&props.row.changeStatus == 3, }"
                    >{{ props.row.subName }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="score"
                :label="$t('culture.courseCategory.credit')"
                width="100px"
            >
                <template slot-scope="props">
                    <el-input
                        v-if="!isRead"
                        v-model="props.row.score"
                        type="text"
                        @focus="focusInput(props.row)"
                        @blur="blurInput(props.row)"
                        @change="markStatus(props.row, props.$index)"
                    />
                    <span v-if="isRead">{{ props.row.score }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="percent"
                :label="$t('culture.courseCategory.percent')"
                align="center"
            >
                <template
                    v-if="props.row.labelId !== ''"
                    slot-scope="props"
                >{{ getPercent(props.row) }}</template>
            </el-table-column>
        </el-table>
        <el-row v-if="next" class="pd-12px float-right" style="padding-right: 0;">
            <el-col :span="24">
                <el-button
                    size="medium"
                    @click="backStep"
                >{{ $t('culture.courseCategory.backStep') }}</el-button>
                <el-button v-if="!isRead" size="medium" @click="save(null)">{{$t('message.save')}}</el-button>
                <el-button
                    size="medium"
                    type="primary"
                    @click="nextStep"
                >{{ $t('culture.courseCategory.nextStep') }}</el-button>
            </el-col>
        </el-row>

        <el-dialog
            :visible.sync="showDialog"
            :before-close="handleClose"
            :title="$t('culture.courseCategory.chooseDirection')"
            width="34%"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <el-card shadow="never" body-style="padding: 24px;">
                <el-table
                    ref="directionTable"
                    :span-method="arraySpanMethod"
                    :data="directions"
                    border
                    @selection-change="handleSelectionChange"
                >
                    <el-table-column align="center" :label="$t('culture.profession.directionCode')">
                        <template slot-scope="props">{{ props.row.code }}</template>
                    </el-table-column>
                    <el-table-column align="center" :label="$t('culture.profession.directionName')">
                        <template slot-scope="props">{{ props.row.name }}</template>
                    </el-table-column>
                    <el-table-column type="selection" width="55"/>
                </el-table>
            </el-card>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showDialog = false">{{ $t('message.cancel') }}</el-button>
                <el-button type="primary" @click="submitDirection">{{ $t('message.confirm') }}</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import {
    saveCourseCategoryForm,
    getCourseCategoryFormById,
    coursesLabelTreeList,
    batchSaveCultureRule,
    findCheckedCultureLabelList
} from "common/src/api/courseTemplate";
import { deleteCultureRule } from "common/src/api/culture/cultureSchemeRule";
import {
    editDirDataByScheme,
    findDirBySchemeId,
    findDirectionLableRel,
    findAllDirection,
    delAllDirection
} from "common/src/api/culture/courseCategoryForm";
import UTILS from "common/src/utils/utils";
import { queryDic } from "common/src/api/dictionary";
import { findCultureSchemeById } from "common/src/api/culture/cultruescheme";
import { findDirMaintenByPro } from "common/src/api/culture/campusProfession";
export default {
    name: "CourseCategoryForm",
    props: {
        next: {
            type: Function,
            default: null
        },
        templateIdOrigin: {
            //此id是原始模板id,用于本页课程学分和原始模板分数校验使用，仅使用于此，与其他无关
            type: Number,
            default: null
        },
        templateId: {
            type: Number,
            default: null
        },
        isRead: {
            type: Boolean,
            default: false
        },
        dataType: {
            type: String,
            default: "1" // 1为模板，2为方案
        },
        inChange: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            tip:
                '"课程类别"会自动关联到相应的学生，请教务员填写每个课程类别的最低学分要求。',
            resCategories: [], // 缓存返回的分类数据
            courseCategories: [], // 原始数据
            processedData: [], // 转换后数据
            directions: [], // 方向选择
            directionCheckeds: [],
            courseOriginData: [], //此数据是模板课程的原始数据，仅用于本页学分校验
            topCategoryLength: 0,
            showDialog: false,
            sum: 0,
            tabs: {},
            topNavItems: [],
            postData: [],
            noDirData: [],
            isDirections: false
        };
    },
    created() {
        this.getCourseCategory();
        this.getAllDirctions();
    },
    methods: {
        markStatus(row, index) {
            row.changeStatus = "2";
        },
        clickItem(item) {
            const self = this;
            self.saveData(false, item);
        },
        // 切换
        toggle(data) {
            this.topNavItems.forEach(item => {
                item.active = item.value === data.value;
            });
        },
        //学分校验
        scopeCheck(callback) {
            const _this = this;
            try {
                _this.processedData.forEach(e => {
                    const checkScore = _this.courseOriginData.find(
                        c => c.labelId * 1 == e.labelId * 1
                    );
                    if (e.score * 1 < checkScore.credit * 1) {
                        _this.prompt("single", e.name);
                        throw "jumpout";
                    }
                });
                const totalScore = _.map(_this.processedData, "score").reduce(
                    function(total, num) {
                        return parseInt(total) + parseInt(num);
                    }
                );
                const isTotalMax =
                    _this.processedData[_this.processedData.length - 1].score *
                        1 >=
                    totalScore -
                        _this.processedData[_this.processedData.length - 1]
                            .score *
                            1;
                callback(isTotalMax);
            } catch (e) {
                console.log(e);
            }
        },
        prompt(type = "total", courseName) {
            if (type == "total") {
                this.$message({
                    type: "warning",
                    message: this.$t("culture.courseCategory.totalScoreLimit")
                });
            } else {
                this.$message({
                    type: "warning",
                    message: `${courseName}${this.$t(
                        "culture.courseCategory.singleScoreLimit"
                    )}`
                });
            }
        },
        saveData(isSubmit, item) {
            const self = this;
            const data = {};
            data.code = self.tabs.value;
            data.list = [];
            this.scopeCheck(state => {
                if (!state) {
                    this.prompt();
                } else {
                    self.processedData.forEach(row => {
                        let cur = {
                            directionCode: self.tabs.value,
                            directionName: self.tabs.label,
                            schemeId: self.templateId,
                            labelId: row.labelId,
                            credit: row.score,
                            total: "",
                            orderNo: row.orderNo
                        };
                        data.list.push(cur);
                    });
                    const index = _.findIndex(self.postData, o => {
                        return o.code === data.code;
                    });
                    if (index === -1) {
                        self.postData.push(data);
                    } else {
                        self.postData[index].list = data.list;
                    }
                    if (isSubmit) {
                        self.submit(null);
                    } else {
                        self.toggle(item);
                        self.tabs = item;
                        self.getDirCourses(self.templateId, item.value);
                    }
                }
            });
        },

        // 输入框获取焦距
        focusInput(row) {
            if (row.score === 0) {
                row.score = "";
            }
        },
        // 输入框失去焦距
        blurInput(row) {
            if (row.score.trim() === "") {
                row.score = 0;
            }
            const value = Number(row.score);
            if (isNaN(value)) {
                row.score = 0;
            } else if (value < 0) {
                row.score = Math.abs(row.score);
            }
        },

        // 上一步
        backStep() {
            if (this.next) {
                this.next(-1);
            }
        },
        // 下一步
        nextStep() {
            this.scopeCheck(state => {
                if (!state) {
                    this.prompt();
                } else {
                    if (this.isRead) {
                        if (this.next) {
                            this.next();
                        }
                    } else {
                        this.submit(() => {
                            if (this.next) {
                                this.next();
                            }
                        });
                    }
                }
            });
        },
        // 获取百分比
        getPercent(row) {
            const scoresArr = this.processedData.map(p => p.score);
            let totalScore = scoresArr.reduce((prev, curr, index) => {
                const value = Number(curr);
                if (!isNaN(value) && scoresArr.length !== index + 1) {
                    return Number(prev) + Number(curr);
                } else {
                    return Number(prev);
                }
            }, 0);

            if (isNaN(totalScore) || totalScore === 0) {
                totalScore = 1;
            }
            return (
                (parseFloat(row.score / totalScore).toFixed(4) * 100).toFixed(
                    2
                ) + "%"
            );
        },
        // 计算合并单元格
        arraySpanMethod({ row, column, rowIndex, columnIndex }) {
            if (columnIndex === 0) {
                if (row.isMixed) {
                    if (row.isFirst) {
                        return {
                            rowspan: row.subLength,
                            colspan: 1
                        };
                    } else {
                        return {
                            rowspan: 0,
                            colspan: 0
                        };
                    }
                }
            }
            if (columnIndex === 5) {
                if (row.isMixed) {
                    if (row.isFirst) {
                        return {
                            rowspan: row.subLength,
                            colspan: 1
                        };
                    } else {
                        return {
                            rowspan: 0,
                            colspan: 0
                        };
                    }
                }
            }
        },
        //获取方向下所有的课程分类信息
        getDirCourses(schemeId, directionCode) {
            const self = this;
            findDirectionLableRel(schemeId, directionCode).then(res => {
                if (res.code == 200) {
                    if (res.data[directionCode]) {
                        for (const item of res.data[directionCode]) {
                            for (const o of self.processedData) {
                                if (item.labelId === o.labelId) {
                                    o.score = item.credit;
                                    if (o.labelId === "") {
                                        if (o.score === "0" || o.score === "") {
                                            o.score = self.sum;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            });
        },
        // 获取课程分类  如果是专业大类，则没有方向
        getCourseCategory() {
            getCourseCategoryFormById(this.templateId, this.dataType).then(
                response => {
                    if (response.code === 200) {
                        if (
                            response.data.cultureRuleList &&
                            response.data.cultureRuleList.length > 0
                        ) {
                            this.resCategories = response.data.cultureRuleList;
                            this.__fromatData(response.data.cultureRuleList);
                        }
                    }
                }
            );
            /*  } */
        },
        //获取方向名称
        getDireStr(code) {
            for (const i of this.directions) {
                if (code === i.code) {
                    return i.name;
                }
            }
        },
        getCredit(row) {
            if (row.score) {
                return row.score;
            } else {
                return row.credit;
            }
        },
        save(callback) {
            this.saveData(true);
        },
        submit(callback) {
            if (this.processedData.length === 0) {
                this.$message({
                    type: "warning",
                    message: "没有课程类别，请联系管理员处理课程类别数据问题！"
                });
                return;
            }
            if (this.isDirections) {
                const data = [];
                const self = this;
                for (var i = 0; i < self.postData.length; i++) {
                    self.postData[i].list.forEach(row => {
                        let cur = {
                            directionCode: self.postData[i].code,
                            directionName: self.getDireStr(
                                self.postData[i].code
                            ),
                            schemeId: self.templateId,
                            labelId: row.labelId,
                            credit: self.getCredit(row),
                            total: "",
                            orderNo: row.orderNo
                        };
                        data.push(cur);
                    });
                }
                console.log(data);
                editDirDataByScheme(data).then(res => {
                    if (res.code == 200) {
                        if (res.code === 200) {
                            this.$message({
                                type: "success",
                                message: this.$t("message.saveSuccess")
                            });
                            if (callback) {
                                callback();
                            }
                        }
                    }
                });
            } else {
                const data = {
                    id: this.templateId,
                    cultureRuleList: []
                };
                this.processedData.forEach(row => {
                    let cur = {
                        id: row.id,
                        labelId: row.labelId,
                        credit: row.score,
                        type: this.dataType,
                        orderNo: row.orderNo
                    };
                    if (
                        row.hasOwnProperty("changeStatus") &&
                        row.changeStatus == "2"
                    )
                        cur.changeStatus = "2";
                    data.cultureRuleList.push(cur);
                });
                saveCourseCategoryForm(data).then(response => {
                    if (response.code === 200) {
                        this.$message({
                            type: "success",
                            message: this.$t("message.saveSuccess")
                        });
                        if (callback) {
                            callback();
                        }
                    }
                });
            }
        },
        // 转换原始数据为视图数据
        __convert() {
            const largeCategories = this.courseCategories.filter(
                c => c.pid === "0"
            );
            const result = [];
            largeCategories.forEach(large => {
                const smallCategories = this.courseCategories.filter(
                    small => small.pid === large.labelId
                );
                // 是否存在子分类
                if (smallCategories.length > 0) {
                    let isFirst = true;
                    smallCategories.forEach(small => {
                        result.push({
                            id: small.id,
                            labelId: small.labelId,
                            name: large.name,
                            score: small.score,
                            subName: small.name,
                            level: small.level,
                            pid: large.labelId,
                            plevel: large.level,
                            isFirst: isFirst,
                            subLength: smallCategories.length,
                            orderNo: small.orderNo,
                            porderNo: large.orderNo,
                            isMixed: true, // 包含子分类
                            changeStatus: small.changeStatus
                        });
                        isFirst = false;
                    });
                } else {
                    result.push({
                        id: large.id,
                        labelId: large.labelId,
                        level: large.level,
                        name: large.name,
                        score: large.score,
                        orderNo: large.orderNo,
                        porderNo: large.orderNo,
                        subName: ""
                    });
                }
            });
            this.processedData = result;
            this.noDirData = result;
            console.log(this.noDirData);
            this.getSumStr(result);
            this.getCheckedDirctions();
            this.getDirecs();
        },
        getSumStr(data) {
            let temp = 0;
            for (const item of data) {
                if (item.labelId) {
                    temp += Number(item.score);
                }
            }
            this.sum = temp.toString();
        },
        // 格式化课程分类数据
        __fromatData(data) {
            this.topCategoryLength = data.filter(o => o.level === "1").length;
            this.courseCategories.length = 0;
            data[data.length - 1].level = 999;
            data = _.sortBy(data, ["orderNo", "level"]);
            if (data && data.length > 0) {
                data.forEach(row => {
                    if (row.labelId) {
                        this.courseCategories.push({
                            id: row.id,
                            labelId: row.labelId,
                            level: row.level,
                            name: row.label,
                            pid: row.parentId,
                            score: row.credit,
                            orderNo: row.orderNo,
                            changeStatus: row.changeStatus
                        });
                    } else {
                        this.courseCategories.push({
                            id: row.id,
                            labelId: "",
                            name: "合计",
                            pid: "0",
                            score: row.credit,
                            orderNo: row.orderNo
                        });
                    }
                });
            } else if (data) {
                data.coursesLabelList.forEach(row => {
                    this.courseCategories.push({
                        id: row.id,
                        labelId: row.labelId,
                        name: row.label,
                        pid: row.parentId,
                        score: row.credit,
                        orderNo: row.orderNo
                    });
                });
            }
            this.__convert();
        },
        //获取所有方向
        getAllDirctions() {
            const params = {
                id: this.templateId
            };
            const self = this;
            const query = {};
            findCultureSchemeById(params).then(res => {
                if (res.code == 200) {
                    query.professionCode = res.data.campusProfession;
                    query.grade = res.data.grade;
                    findDirMaintenByPro(query).then(res => {
                        if (res.code == 200) {
                            //if(res.data&&res.data.list>0){
                            self.directions = res.data;
                        }
                    });
                }
            });
            //获取原始课程数据
            getCourseCategoryFormById(this.templateIdOrigin, "1")
                .then(res => {
                    if (res.code === 200) {
                        this.courseOriginData =
                            res.data.cultureRuleList.length > 0 &&
                            res.data.cultureRuleList;
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },

        // 获取方向，回显已有方向
        getCheckDirctions() {
            const self = this;
            const checkedIndexs = [];
            findDirBySchemeId(self.templateId).then(res => {
                if (res.data && res.code === 200) {
                    _.forEach(_.map(res.data, "directionCode"), item => {
                        checkedIndexs.push(
                            _.findIndex(self.directions, o => {
                                return o.code === item;
                            })
                        );
                    });
                    _.forEach(checkedIndexs, index => {
                        if (index !== -1) {
                            this.$refs.directionTable.toggleRowSelection(
                                self.directions[index]
                            );
                        }
                    });
                }
            });
        },

        // 获取改模板下的所有方向
        getCheckedDirctions() {
            const self = this;
            findDirBySchemeId(this.templateId).then(res => {
                if (res.code == 200) {
                    if (res.data && res.data.length > 0) {
                        const temp = [];
                        res.data.forEach(row => {
                            temp.push({
                                label: row.directionName,
                                value: row.directionCode,
                                active: false
                            });
                        });
                        self.topNavItems = temp;
                        self.topNavItems = _.sortBy(this.topNavItems, [
                            "value"
                        ]);
                        this.isDirections = true;
                        this.tabs = this.topNavItems[0];
                        this.topNavItems[0].active = true;
                        self.getDirCourses(
                            self.templateId,
                            self.topNavItems[0].value
                        );
                    }
                }
            });
        },
        //获取所有方向，放到数组中
        getDirecs() {
            const self = this;
            findAllDirection(self.templateId).then(res => {
                if (res.code == 200) {
                    for (var index in res.data) {
                        const data = {};
                        data.list = [];
                        data.code = index;
                        let temp = _.cloneDeep(self.noDirData);
                        for (const item of res.data[index]) {
                            for (const o of temp) {
                                if (item.labelId === o.labelId) {
                                    o.score = item.credit;
                                    if (o.labelId === "") {
                                        if (o.score === "0" || o.score === "") {
                                            o.score = self.sum;
                                        }
                                    }
                                }
                            }
                            data.list = temp;
                        }
                        self.postData.push(data);
                    }
                }
            });
        },

        addDirection() {
            this.getCheckDirctions();
            this.showDialog = true;
        },
        submitDirection() {
            const self = this;
            self.topNavItems = [];
            if (self.directionCheckeds.length > 0) {
                const temp = [];
                const checkedIndexs = [];
                for (let dirChecked of self.directionCheckeds) {
                    self.topNavItems.push(dirChecked);
                    const data = {};
                    data.code = dirChecked.value;
                    data.list = self.noDirData;
                    temp.push(data);
                }
                for (let item of self.postData) {
                    checkedIndexs.push(
                        _.findIndex(temp, o => {
                            return o.code === item.code;
                        })
                    );
                }
                for (let index of checkedIndexs) {
                    if (index !== -1) {
                        for (let item of self.postData) {
                            if (temp[index].code == item.code) {
                                temp[index].list = item.list;
                            }
                        }
                    }
                }
                this.isDirections = true;
                self.topNavItems = _.sortBy(this.topNavItems, ["value"]);
                (this.isDirections = true), (this.tabs = this.topNavItems[0]);
                this.topNavItems[0].active = true;
                self.postData = temp;
                self.submit();
            } else {
                this.isDirections = false;
                this.delDirections();
            }
            this.showDialog = false;
        },
        delDirections() {
            delAllDirection(this.templateId).then(res => {
                if (res.code == 200) {
                    this.$message({
                        type: "success",
                        message: this.$t("message.saveSuccess")
                    });
                }
            });
        },
        handleSelectionChange(checkeds) {
            const self = this;
            self.directionCheckeds = [];
            if (checkeds.length === 0) return;
            _.forEach(checkeds, item => {
                if (item) {
                    self.directionCheckeds.push({
                        label: item.name,
                        value: item.code,
                        active: false
                    });
                }
            });
        }
    }
};
</script>
<style lang="scss" scoped>
.tip-message {
    margin: 10px 0;
    font-size: 14px;
    color: #909090;
}
.float-left {
    span {
        cursor: pointer;
        display: inline-block;
        padding-right: 10px;
    }
    span.active {
        color: #2876c2;
    }
}
</style>
